<?php

namespace app\api\controller\live;

use app\admin\model\system\SystemAttachment;
use app\models\live\LiveManager;
use app\models\live\Live;
use app\models\live\LiveClass;
use app\models\live\LiveRecord;
use app\models\live\LiveShut;
use app\models\live\LiveKick;
use app\models\record\Coinrecord;
use app\Request;
use wanyue\services\upload\Upload;
use wanyue\services\UtilService;
use app\models\user\User;
use app\models\user\UserAttent;
use app\Redis;

class LiveController
{

    //精选列表
    public function featured(Request $request)
    {

        list($page, $limit) = UtilService::getMore([
            [['page', 'd'], 1],
            [['limit', 'd'], 20]
        ], $request, true);

        $banner = sys_data('routine_home_banner') ?: [];
        $list = Live::getList((int)$page, (int)$limit);
        $liveclass=LiveClass::getList();

        $data1=['id'=>-1,'name'=>'关注'];
        $data2=['id'=>0,'name'=>'精选'];

        array_unshift($liveclass,$data2);
        array_unshift($liveclass,$data1);

        return app('json')->successful(compact('banner','liveclass', 'list'));

    }

    //直播分类
    public function liveclass(Request $request)
    {

        $list = LiveClass::getList();

        return app('json')->successful($list);

    }

    //分类下直播
    public function classlive(Request $request,$classid)
    {

        list($page, $limit) = UtilService::getMore([
            [['page', 'd'], 1],
            [['limit', 'd'], 20]
        ], $request, true);

        $list = Live::getClassList($classid,(int)$page, (int)$limit);

        return app('json')->successful($list);

    }

    //关注直播
    public function follow(Request $request)
    {
        list($page, $limit) = UtilService::getMore([
            [['page', 'd'], 1],
            [['limit', 'd'], 15]
        ], $request, true);

        $uid=$request->uid();

        $list = Live::getFollowList($uid, (int)$page, (int)$limit);

        return app('json')->successful($list);

    }

    //搜索直播
    public function search(Request $request)
    {

        list($keyword, $page, $limit) = UtilService::getMore([
            ['keyword', ''],
            [['page', 'd'], 1],
            [['limit', 'd'], 20]
        ], $request, true);

        if($keyword==='') return app('json')->fail('请输入关键词');
        $list = Live::search($keyword,(int)$page, (int)$limit);

        return app('json')->successful($list);

    }

    /**
     * 直播配置
     */
    public function config(Request $request)
    {
        /* IOS分辨率 -腾讯版
            0 360_640
            1 540_960
            2 720_1280

           安卓分辨率 -腾讯版
            0 360_640
            1 540_960
            2 720_1280
        */

        $ios=[
            'codingmode' => '2',  //编码 0自动，1软编，2硬编
            'resolution' => '1',  //分辨率
            'isauto' => '1',  //是否自适应 0否1是
            'fps' => '20',  //帧数
            'fps_min' => '20',  //最低帧数
            'fps_max' => '30',  //最高帧数
            'gop' => '3',  //关键帧间隔
            'bitrate' => '800',  //初始码率  kbps
            'bitrate_min' => '500',  //最低码率
            'bitrate_max' => '800',  //最高码率
            'audiorate' => '44100',  //音频采样率  Hz
            'audiobitrate' => '48',  //音频码率 kbps

            'preview_fps' => '15',  //预览帧数
            'preview_resolution' => '1',  //预览分辨率
        ];
        $android=[
            'codingmode' => '3',  //编码 1自动，3软编，2硬编
            'resolution' => '0',  //分辨率
            'isauto' => '1',  //是否自适应 0否1是
            'fps' => '20',  //帧数
            'fps_min' => '20',  //最低帧数
            'fps_max' => '30',  //最高帧数
            'gop' => '3',  //关键帧间隔
            'bitrate' => '500',  //初始码率  kbps
            'bitrate_min' => '500',  //最低码率
            'bitrate_max' => '800',  //最高码率
            'audiorate' => '44100',  //音频采样率  Hz
            'audiobitrate' => '48',  //音频码率 kbps

            'preview_fps' => '15',  //预览帧数
            'preview_resolution' => '1',  //预览分辨率
        ];


        return app('json')->successful(compact('ios','android'));
    }

    /**
     * 开播
     */
    public function start(Request $request)
    {

        list($title, $thumb, $classid, $province, $city, $deviceinfo,$source) = UtilService::postMore([
            ['title',''],
            ['thumb',''],
            ['classid','0'],
            ['province',''],
            ['city',''],
            ['deviceinfo',''],
            ['source',''],
        ], $request, true);

        $res = Live::setLive($request->uid(), $title,$classid,$thumb,$province,$city,$deviceinfo,$source);
        if (!$res) return app('json')->fail(Live::getErrorInfo());

        return app('json')->successful($res);
    }

    /**
     * 更新状态
     */
    public function upLive(Request $request)
    {
        list($islive) = UtilService::postMore([
            ['islive','0'],
        ], $request, true);
        $res = Live::upIslive($request->uid(), $islive);
        return app('json')->successful('ok');
    }


    /**
     * 关播
     */
    public function stop(Request $request)
    {
        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);

        $uid_r=$request->uid();

        $stream_a=explode('_',$stream);
        $uid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';
        if($uid_r!=$uid) return app('json')->fail('无权操作!');

        $res = Live::stopLive($uid,$showid);
        if (!$res) return app('json')->fail(Live::getErrorInfo());

        return app('json')->successful('关播成功');
    }


    /**
     * 检测直播
     */
    public function check(Request $request)
    {
        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);
        $uid=$request->uid();

        if($stream=='') return app('json')->fail('参数错误');
        $stream_a=explode('_',$stream);
        $liveuid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';

        if($uid==$liveuid) return app('json')->fail('不能进入自己的直播间');
        $where=[
            'uid'=>$liveuid,
            'showid'=>$showid,
            'islive'=>1,
        ];
        $liveinfo = Live::getInfo($where);
        if (!$liveinfo || $liveinfo['islive']!=1) return app('json')->fail('直播已结束或还未开播');
        if(LiveKick::isKick($uid,$liveuid)) return app('json')->fail('您已被踢出直播间，无法进入');
        return app('json')->successful('');
    }

    /**
     * 进入直播间
     */
    public function enter(Request $request)
    {

        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);
        $uid=$request->uid();

        $stream_a=explode('_',$stream);
        $liveuid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';



        if($uid==$liveuid) return app('json')->fail('不能进入自己的直播间');

        $where=[
            'uid'=>$liveuid,
            'showid'=>$showid,
            'islive'=>1,
        ];
        $liveinfo = Live::getInfo($where);
        if (!$liveinfo) return app('json')->fail('直播已结束或还未开播');

        if(LiveKick::isKick($uid,$liveuid)) return app('json')->fail('您已被踢出直播间，无法进入');

        $ishut=LiveShut::isShut($uid,$liveuid);
        $chatserver = sys_config('chatserver');

        $token=md5(md5($uid));
        $userinfo=User::getUserInfoByRedis($uid);
        $userinfo['sign']=0;
		//用户管理员与超管查询
		$usertype=LiveManager::checkmanager($uid,$liveuid);
		$userinfo['usertype']=$usertype;
		$userinfo['stream']=$stream;
	//	$userinfo['usertype']=0;
        Redis::set($token,$userinfo);

        $isattent=UserAttent::isAttent($uid,$liveuid);

        $liveuidinfo=User::getUserInfoByRedis($liveuid);

        $likes=NumberFormat($liveinfo['likes']);

        $goods=NumberFormat($liveinfo['goods']);

        $stream=$liveuid.'_'.$showid;
        $pull=$liveinfo['pull'];
        $isvideo=$liveinfo['isvideo'];
        if(!$isvideo){
            $pull=Live::getStreamUrl($stream);
        }

        $nickname=$liveuidinfo['nickname'];
        $avatar=$liveuidinfo['avatar'];

        //累计人数梳理
        Live::setNums($uid,$liveuid,$showid);

        $liveinfo2 = Live::getInfo($where);
        //$nums=NumberFormat($liveinfo2['nums']);
        $nums=NumberFormat(Redis::zCard('user_'.$stream));

        return app('json')->successful(compact('chatserver','token', 'isattent','ishut','pull','liveuid','nickname','avatar','stream','likes','nums','isvideo','goods','usertype'));
    }
    /**
     * 关播
     */
    public function stopInfo(Request $request)
    {
        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);

        $stream_a=explode('_',$stream);
        $uid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';

        $length='00:00:00';
        $nums='0';

        $where=[
            'uid'=>$uid,
            'showid'=>$showid,
        ];
        $res = LiveRecord::getInfo($where);
        if($res){
            $cha=$res['endtime']-$res['starttime'];
            $length=handel_time_length($cha,1);
            $nums=NumberFormat($res['nums']);
        }

        return app('json')->successful(compact('length','nums'));
    }

    /**
     * 获取房间人数
     */
    public function getnums(Request $request)
    {
        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);

/*         $stream_a=explode('_',$stream);
        $liveuid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';

        $where=[
            'uid'=>$liveuid,
            'showid'=>$showid,
        ];
        $info=Live::getInfo($where); */

		$nums=Redis::zCard('user_'.$stream);


/*         $nums=0;
        if($info){
            $nums=$info['nums'];
        }
        $nums=NumberFormat($nums);
 */
        return app('json')->successful(compact('nums'));
    }

    /**
     * 获取点赞数
     */
    public function getlikes(Request $request)
    {
        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);

        $stream_a=explode('_',$stream);
        $liveuid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';
        $where=[
            'uid'=>$liveuid,
            'showid'=>$showid,
        ];
        $info=Live::getInfo($where);
        $nums=0;
        if($info){
            $nums=$info['likes'];
        }
        $nums=NumberFormat($nums);

        return app('json')->successful(compact('nums'));
    }

    /**
     * 点赞
     */
    public function setlike(Request $request)
    {
        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);

        $uid=$request->uid();
        $stream_a=explode('_',$stream);
        $liveuid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';

        $res=Live::setLikes($liveuid,$showid);

        if (!$res) return app('json')->fail(Live::getErrorInfo());

        $where=[
            'uid'=>$liveuid,
            'showid'=>$showid,
        ];
        $info=Live::getInfo($where);
        $nums=0;
        if($info){
            $nums=$info['likes'];
        }

        return app('json')->successful('操作成功',compact('nums'));
    }

    /**
     * 本次直播销售商品数
     */
    public function getgoodsnums(Request $request)
    {
        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);

        $stream_a=explode('_',$stream);
        $liveuid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';
        $where=[
            'uid'=>$liveuid,
            'showid'=>$showid,
        ];
        $info=Live::getInfo($where);
        $nums=0;
        if($info){
            $nums=$info['goods'];
        }
        $nums=NumberFormat($nums);
        return app('json')->successful(compact('nums'));
    }

    /**
     * 检测是否直播中
     */
    public function checklive(Request $request)
    {
        list($stream) = UtilService::postMore([
            ['stream',''],
        ], $request, true);

        $uid=$request->uid();
        $stream_a=explode('_',$stream);
        $liveuid = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';

        $islive=0;
        $info=Live::islive($liveuid);
        if($info && $info['showid']==$showid) $islive=1;

        return app('json')->successful('操作成功',compact('islive'));
    }

    /**
     * 根据主播ID获取直播信息
     */
    public function getinfo(Request $request)
    {
        list($liveuid) = UtilService::getMore([
            ['liveuid',''],
        ], $request, true);

        $uid=$request->uid();
        if($uid==$liveuid) return app('json')->fail('不能进入自己的直播间');

        $where=['uid'=>$liveuid,'islive'=>1];
        $info=Live::getInfo($where);
        if(!$info)  return app('json')->fail('直播已结束或还未开播');

        if(LiveKick::isKick($uid,$liveuid)) return app('json')->fail('您已被踢出直播间，无法进入');

        $info=$info->toArray();

        $info['likes']=NumberFormat($info['likes']);
        $info['nums']=NumberFormat($info['nums']);
        $stream=$info['uid'].'_'.$info['showid'];
        $info['stream']=$stream;
        if(!$info['isvideo']){
            $info['pull']=Live::getStreamUrl($stream);
        }

        $nickname='';
        $avatar='';
        $userinfo=User::getUserInfoByRedis($info['uid']);
        if($userinfo){
            $nickname=$userinfo['nickname'];
            $avatar=$userinfo['avatar'];
        }
        $info['nickname']=$nickname;
        $info['avatar']=$avatar;

        if($info['thumb']=='') $info['thumb']=$avatar;

        unset($info['offtime']);
        unset($info['isoff']);
        unset($info['deviceinfo']);
        unset($info['starttime']);

        return app('json')->successful($info);
    }
    /**
     * 用户列表
     */
    public function getUserList(Request $request)
    {
        list($stream,$liveuid,$p) = UtilService::getMore([
			['stream',''],
            [['liveuid','d'],0],
            [['p','d'],0],
        ], $request, true);
		$uid=$request->uid();
/* 		$uid=$_GET['uid'];
		$p=$_GET['p'];
		$stream=$_GET['stream']; */

        $stream_a=explode('_',$stream);
        $liveuida = isset($stream_a[0])? $stream_a[0] : '0';
        $showid = isset($stream_a[1])? $stream_a[1] : '0';
		if($liveuid != $liveuida){
			return app('json')->fail('参数错误');
		}

		$p=$p>1?$p:1;
		$pnum=20;
		$start=($p-1)*$pnum;
		$uidlist=Redis::zRevRange('user_'.$stream,$start,$pnum,true);

		$lista=[];
		if($uidlist){
            foreach($uidlist as $k=>$v){
				//if($k !=$uid){
					$userinfo=User::getUserInfo($k,'uid,avatar,nickname');
					$where=[
						'uid'=>$userinfo['uid'],
						'showid'=>$showid,
					];
					$coininfo = Coinrecord::field('SUM(totalcoin) as total')->where($where)->find();
					$datalist= [
						'uid'=>$userinfo['uid'],
						'avatar'=>$userinfo['avatar'],
						'nickname'=>$userinfo['nickname'],
						'total'=>$coininfo['total']?$coininfo['total']:0
					];
					$lista[]=$datalist;

				//}

            }
		}

		return app('json')->successful($lista);
    }

    /***
     * 检测用户是否被禁言
     */
    public function checkshutup(Request $request){
        list($liveuid) = UtilService::getMore([
            ['liveuid',''],
        ], $request, true);
		$uid=$request->uid();


        $where = ['uid'=>$uid,'liveuid'=>$liveuid];
        $info = LiveShut::isShut($uid,$liveuid);

        $rs = ['status'=>$info];
		return app('json')->successful($rs);
    }

}
